package cn.imu.servlet;

import cn.imu.dao.LoginDao;
import cn.imu.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    ///控制器层：接受view请求，并分发给Model进行处理
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理登录
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("uname");
        String pwd=request.getParameter("upwd");
        User user=new User(name,pwd);


        response.setCharacterEncoding("utf-8");//响应编码
        response.setContentType("text/html;charset=UTF-8");//展示时的编码

        //将用户名添加到Cookie中
        Cookie cookie=new Cookie("uname",name);
        cookie.setMaxAge(360);//秒为单位

        //调用model层的登录功能
        int result= LoginDao.login(user);

        response.addCookie(cookie);
        request.setAttribute("users",user);
        if(result>0){//登录成功
            System.out.println("登录成功！！！！");
            //登录成功后，将username放入到session中,同时监听session的属性变化
            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("LoginSuccess(main).jsp").forward(request,response);
            System.out.println("请求转发成功！！！！");
            //response.sendRedirect("LoginSuccess(main).jsp");
        }else if(result<0){
            System.out.println("系统异常！！！");
        }else{
            System.out.println("登录失败，用户名或密码错误!!!!");
            response.sendRedirect("Login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
